package br.com.zanictech.grails.broker


class Servidor {
	
	public static Map SERVIDORES = [:]

    static constraints = {
		nome blank: false
    }
	
	static transients = ['executando', 'thread', 'server']
	
	String nome
	String ip
	int porta
	Thread thread = new Thread()

	boolean executando = false
	ServerSocket server
	
	String toString() {
		return "${nome} - ${ip} : ${porta}"
	}
	
	def stop() throws Exception {
		SERVIDORES.remove(this)
		executando = false
		server.close()
		//server = null
		thread.interrupt()
	}
	
	def start() throws Exception {
		SERVIDORES.put(id, this)
		executando = true
		
		thread.start {

			SocketAddress address = new InetSocketAddress(porta)
			server = new ServerSocket()
			server.setReuseAddress(true)
			
			log.debug " >>>> SUPERLOG: ${server.isBound()}, ${server.getReuseAddress()}"
			
			def count = 0
			while(!server.isBound()) {
				log.debug "Tentando realizar o bind: ${count++}"
				if(!server.isBound()) {
					server.bind(address)
				}
			}
			
			while(executando) {
				println "Servidor executando: ${executando}. Aguardando conexão... ${new Date()}"
				server.accept { socket ->
					println "processing new connection..."
					socket.withStreams { input, output ->
						
						def reader = input.newReader()
						def buffer = reader.readLine()
						
						while(!buffer.equals("Bye")) {
							println "server received: $buffer"
							def now = new Date()
							output << "echo-response($now): " + buffer + "\n"
							reader = input.newReader()
							buffer = reader.readLine()
						}
						output << buffer + "\n"
					}
					println "processing/thread complete."
				}
			}
		}
	}
}
